<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
    <div style="display: flex; align-items: center; padding: 1px 15px; position: relative;">
      <!-- 左侧新建按钮 -->
      <el-button class="idoo-details-add">新建</el-button>
      <!-- 右侧信息区域：垂直展示 -->
      <div style="display: flex; flex-direction: column; margin-left: 10px;">
        <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">租户</el-button></span>
        <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
          <span class="sub-title">{{ detailsTitle }}</span>
          <el-tooltip content="保存" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
              <UploadFilled />
            </el-icon>
          </el-tooltip>
          <el-tooltip content="撤销修改" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleRevert">
              <RefreshLeft />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 带阴影的分割线 -->
    <div class="divider"></div>
    <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
    <div class="content-section">
      <div style="display: flex; width: 100%;">

        <!-- 左侧：无阴影的Card，占整体宽度的65%，用于表单的详情数据 -->
        <div style="height: auto; width: 65%; overflow-y: auto; margin-right: 10px;">
          <el-card style="box-shadow: none;">
            <el-form :model="deptForm" style="width: 100%;">
              <el-form-item label="" prop="cusName">
                <el-input v-model="deptForm.deptName"
                  style="font-size: 30px; height: 60px; line-height: 60px; width: 70%; padding: 10px;"
                  class="idoo-details-input" placeholder="部门名称：例如：采购部"></el-input>
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="部门负责人">
                    <el-input v-model="deptForm.deptManager" style="width: 100%;" class="idoo-details-input"
                      placeholder="请填写负责人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="标签">
                    <el-input v-model="deptForm.deptLabel" style="width: 100%;" class="idoo-details-input"
                      placeholder="部门标签"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="排序">
                    <el-input v-model="deptForm.sort" class="idoo-details-input" placeholder="部门名称：例如：采购部"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12"></el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="说明">
                    <el-input type="textarea" v-model="deptForm.deptRemark" class="idoo-details-input"
                      placeholder="说明"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </div>

        <!-- 右侧：修改记录区域，保持背景色 -->
        <div style="width: 35%; padding: 5px; overflow-y: auto;" v-if="formId">
          <!-- 按钮行 -->
          <div style="display: flex;margin-bottom: 10px;">
            <el-button :icon="Edit" :class="recordRemark ? 'idoo-details-add' : 'el-button-primary'"
              :type="recordRemark ? 'primary' : ''" @click="recordRemarkChoose"></el-button>
            <el-button :icon="Search" :class="recordSearch ? 'idoo-details-add' : 'el-button-primary'"
              :type="recordSearch ? 'primary' : ''" @click="recordSearchChoose"></el-button>

            <el-input ref="searchRef" v-if="recordSearch" v-model="recordSearchInfo" placeholder="搜索：操作记录内容：操作人/字段名称/内容"
              style="margin-left: 50px;width:60%">
              <template #append>
                <el-button :icon="Search" @click="recordSearching" style="display:inherit !important;" />
              </template>
            </el-input>
          </div>
          <div v-if="recordRemark">
            <el-input type="textarea" v-model="recordRemarkInfo" class="record-remark-textarea"
              placeholder="记录详情内部说明..." style="width: 70%;"></el-input>
          </div>
          <div style="margin-top: 5px;" v-if="recordRemark">
            <el-button type="primary" @click="sendRecordRemark" size="large"
              style="width: 60px; height: 35px; font-size: small;">发送</el-button>
          </div>
          <!-- 操作记录组件 -->
          <DepartmentRecord :recordInfos="recordInfos" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { UploadFilled, RefreshLeft, Edit, Search } from '@element-plus/icons-vue';
import router from '@/router';
import { ElMessageBox } from 'element-plus';
import { _getDepartmentInfo, _getRecordInfos, _modifyDepartmentInfo, _saveDepartmentInfo, _saveRecordRemarkInfos, _searchRecordRemarkInfos } from '@/api/generic/employess/department/list-api';
import type { DepartmentForm } from '@/types/employess/department/types';
import { getChangedFields, updateWrapperBuilder } from '@/utils/form/updateFormHelper';
import type { BaseRecordVo } from '@/types/basetypes';
import DepartmentRecord from '@/components/base/record/IdooRecord.vue';
const route = useRoute();
const detailsTitle = ref("");
const isFormChanged = ref(false);
let formId = route.query.id || "";
const recordInfos = ref<BaseRecordVo[]>([]);
const recordRemark = ref(false);
const recordRemarkInfo = ref("");
const recordSearch = ref(false);
const recordSearchInfo = ref("");
const searchRef = ref(null);
//是否打开业务选择器
const showDialog = ref(false);

// 初始化表单数据
const deptForm = ref<DepartmentForm>({
  /** 部门名称*/
  deptName: '',
  /** 上级部门id*/
  pId: '',
  /**上级部门名称 */
  pDeptName: '',
  /** 部门层级路径 */
  deptLevelPath: '',
  /**部门负责人（staffId）*/
  deptManager: '',
  /**排序*/
  sort: 0,
  /**子部门数量*/
  deptChildrenCount: 0,
  /**员工数量 */
  deptStaffCount: 0,
  /**部门备注*/
  deptRemark: '',
  /**部门标签*/
  deptLabel: '',
})
const originalFormData = ref<DepartmentForm>({});
originalFormData.value = JSON.parse(JSON.stringify(deptForm.value));

const recordRemarkChoose = () => {
  recordRemark.value = !recordRemark.value;
  if (recordRemark.value) {
    nextTick(() => {
      const textarea = document.querySelector('.el-textarea__inner') as HTMLTextAreaElement;
      textarea.focus();
    });
  }
}

const recordSearchChoose = () => {
  recordSearch.value = !recordSearch.value;
  if (recordSearch.value) {
    nextTick(() => {
      if (searchRef.value) {
        const a = searchRef.value as HTMLTextAreaElement;
        a.focus();
      }
    });
  }
}

const resetForm = () => {
  originalFormData.value = JSON.parse(JSON.stringify(deptForm.value));
  detailsTitle.value = deptForm.value.deptName || '新建';
  isFormChanged.value = false;
}

// 监听表单变化
watch(() => deptForm.value, (newVal) => {
  console.log(deptForm.value);
  console.log(originalFormData.value)
  isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
}, { deep: true });

//初始化加载数据
onMounted(async () => {
  detailsTitle.value = '新建'
  console.error(showDialog.value)
  //获取用户数据
  if (formId) {
    //编辑
    const res = await _getDepartmentInfo({ id: formId.toString() });
    if (res.code === 200 && res.data) {
      deptForm.value = res.data;
      originalFormData.value = JSON.parse(JSON.stringify(res.data));
      detailsTitle.value = deptForm.value.deptName || '';
    }
    const rres = await _getRecordInfos({ id: formId.toString() });
    console.log(rres.code);
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
  }
  console.log("onMounted", deptForm.value)
});
//返回按钮
const handleBack = () => {
  if (isFormChanged.value) {
    ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await handleSave();
    }).catch(() => {
      router.push({ path: route.fullPath.replace('/add', '') })
    })
  } else {
    router.push({ path: route.fullPath.replace('/add', '') })
  }
}
//发送备注消息
const sendRecordRemark = async () => {
  if (formId && recordRemark.value) {
    await _saveRecordRemarkInfos({
      bizId: formId.toString(),
      remark: recordRemarkInfo.value.toString(),
    })
    //刷新操作记录
    const rres = await _getRecordInfos({ id: formId.toString() });
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
    recordRemarkInfo.value = '';
  }
}
//搜索备注内容
const recordSearching = async () => {
  if (formId && recordSearch.value) {
    const ress = await _searchRecordRemarkInfos({
      _search_bizid: formId.toString(),
      _search_content: recordSearchInfo.value
    })
    if (ress.code === 200 && ress.data) {
      recordInfos.value = ress.data;
    }
  }
}
// 保存处理函数
const handleSave = async () => {
  //TODO 表单校验
  const formData = deptForm.value
  console.log(originalFormData.value)
  console.log(formData)
  try {
    const i = getChangedFields(originalFormData.value, formData)
    let res;
    if (formId) {
      const upWrap = updateWrapperBuilder(formData, i); // 传递 formData 作为参数
      res = await _modifyDepartmentInfo(upWrap); // 使用 upWrap 作为参数
    } else {
      res = await _saveDepartmentInfo(formData);
      if (res.code === 200 && res.data) {
        formId = res.data[0];
        deptForm.value.id = formId;
      }
    }
    if (res && res.code === 200) {
      resetForm();
      //刷新操作记录
      const rres = await _getRecordInfos({ id: formId.toString() });
      if (rres.code === 200 && rres.data) {
        recordInfos.value = rres.data;
      }
    }
  } catch (error) {
    console.error('保存失败:', error);
  }
};

// 撤销修改，还原表单
const handleRevert = () => {
  deptForm.value = JSON.parse(JSON.stringify(originalFormData.value));
};




</script>
<style scoped>
:deep(.el-input__inner) {
  --el-input-inner-height: none;
}

:deep(.el-card__body) {
  padding: 1% !important;
  justify-content: unset !important;
}

.hover-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hover-icon:hover {
  transform: translateY(-2px);
}

.sub-title {
  font-size: 14px;
  color: #666;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-top: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-section {
  flex: 1;
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs {
  position: relative;
  width: 100%;
}

:deep(.el-tabs__nav-wrap::after) {
  position: absolute;
  content: '';
  width: 100%;
  height: 2px;
  background-color: var(--el-border-color-light);
  bottom: 0;
  left: 0;
  z-index: 1;
}

:deep(.el-tabs__nav.is-top) {
  margin-left: 10px
}

:deep(.el-tabs__header) {
  width: 100%;
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
}
</style>
